<template>
  <div>
    <q-form class="dialog_card column" ref="editRef">
      <div class="row q-col-gutter-x-md dialog_form q-pa-md">
        <div class="col-12">
          <h5><q-icon name="star" color="red" />用户名：</h5>
          <q-input
            lazy-rules
            :rules="[(val) => (val && val.length > 0) || '请输入角色名称']"
            outlined
            dense
            v-model="isform.username"
            type="text"
            clearable
          />
        </div>
        <div class="col-12" v-if="isform.id">
          <h5>密码：</h5>
          <q-input
            type="password"
            autocomplete="new-password"
            lazy-rules
            outlined
            dense
            v-model="isform.new_password"
            clearable
          />
        </div>
        <div class="col-12" v-else>
          <h5><q-icon name="star" color="red" />密码：</h5>
          <q-input
            :rules="[(val) => (val && val.length > 0) || '请输入密码']"
            type="password"
            autocomplete="new-password"
            lazy-rules
            outlined
            dense
            v-model="isform.password"
            clearable
          />
        </div>
        <div class="col-12">
          <h5><q-icon name="star" color="red" />昵称：</h5>
          <q-input
            lazy-rules
            :rules="[(val) => (val && val.length > 0) || '请输入角色描述']"
            outlined
            dense
            v-model="isform.nick_name"
            type="text"
            clearable
          />
        </div>
        <div class="col-12">
          <h5>角色头像：</h5>
          <q-btn round>
            <q-avatar size="100px">
              <el-image
                style="width: 100px; height: 100px"
                :src="imagePath(isform.portrait)"
                :preview-src-list="[imagePath(isform.portrait)]"
                hide-on-click-modal
                preview-teleported
                :initial-index="1"
                fit="cover"
              />
            </q-avatar>
            <yq-uploader
              ref="yqupload"
              @uploadedAvatar="uploadedAvatar"
            ></yq-uploader>
          </q-btn>
          <div>
            <q-btn
              @click="importAvatar"
              color="primary"
              class="color-primary uploadBtn"
              style="margin: 10px 0 5px 5px"
              >点击上传</q-btn
            >
          </div>
        </div>
        <div class="col-12">
          <h5><q-icon name="star" color="red" />角色类型：</h5>
          <q-select
            outlined
            dense
            :rules="[(val) => (val && val !== null) || '请选择角色类型']"
            v-model="isform.role_id"
            option-value="id"
            option-label="name"
            :options="options"
            emit-value
            map-options
            style="width: 50%"
          >
            <template v-slot:no-option>
              <q-item>
                <q-item-section class="text-grey"> No results </q-item-section>
              </q-item>
            </template>
          </q-select>
        </div>
        <div class="col-12">
          <h5>启用状态：</h5>
          <q-toggle
            :false-value="0"
            :true-value="1"
            color="bule"
            v-model="isform.status"
          />
        </div>
      </div>
    </q-form>
  </div>
</template>

<script lang="ts" setup>
import emitter from '@/components/eventbus';
import { userAdd, updateUser } from '@/api/basic';
import { useQuasar } from 'quasar';

interface Props {
  form: {
    id?: string;
    username?: string;
    password?: string;
    portrait?: string;
    nick_name?: string;
    status?: number;
    created_at?: string;
    role?: any;
    role_id?: number;
  };
  useroptions: [];
}
const props = withDefaults(defineProps<Props>(), {
  form: () => ({}),
  useroptions: () => [],
});
const editRef = ref();
const $q = useQuasar();
const yqupload = ref();

//接收兄弟组件传递事件
emitter.on('saveData', async () => {
  console.log('saveDatasaveData');
  IsValidate();
});
//表单验证
const IsValidate = () => {
  if (editRef.value) {
    editRef.value.validate().then(async function (validate: any) {
      if (validate) {
        console.log('验证通过');
        onSubmit();
      } else {
        console.log('验证不通过');
      }
    });
  }
};
//提交数据
const onSubmit = async () => {
  if (isform.value.id) {
    const res: any = await updateUser(isform.value);
    info(res);
    console.log('编辑111', res);
  } else {
    const res: any = await userAdd(isform.value);
    info(res);
    console.log('新建角色111', res);
  }
};
//信息返回
const info = (res: any) => {
  if (res.code == 200) {
    $q.notify({
      color: 'white',
      textColor: 'positive',
      icon: 'check_circle',
      position: 'top',
      message: res.msg,
    });
    emit('backList');
  }
};

//上传图片
const importAvatar = () => {
  yqupload.value.importAvatar();
  // avatarUploader.value.pickFiles();
};
const imagePath = (src: any) => {
  let path = '';
  if (src) {
    if (src.startsWith('http') || src.startsWith('https')) {
      return src;
    }
    path = `${process.env.VUE_APP_API_URL}/${src}`;
  }
  return path;
};
//上传图片回调
const uploadedAvatar = (xhr: any) => {
  console.log('图片状态回调', xhr);
  const response = JSON.parse(xhr.xhr.responseText);
  if (response.code == 200) {
    isform.value.portrait =
      `${process.env.VUE_APP_API_URL}` + response.data.path;
    $q.notify({
      color: 'white',
      textColor: 'positive',
      icon: 'check_circle',
      position: 'top',
      message: response.msg,
    });
    console.log('图片地址:', isform.value.portrait);
  } else {
    $q.notify({
      color: 'white',
      textColor: 'negative',
      icon: 'cancel',
      position: 'top',
      message: response.msg,
    });
  }
  console.log('上传图片完成', xhr, response);
  //清空
  yqupload.value.removeUpload();
};

const emit = defineEmits(['update:form', 'backList']);

const isform: any = computed({
  set(value: any) {
    // emit('update:form', value);
  },
  get() {
    console.log('props.form', props.form);
    return props.form;
  },
});

const options: any = computed({
  set(value: any) {
    // emit('update:form', value);
  },
  get() {
    return props.useroptions;
  },
});
</script>
<style scoped lang="scss"></style>
